# -*- coding: utf-8 -*-
import json
import os
from time import sleep
import filetype
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QDockWidget, QAction, QFileDialog
import cv2
import copy
from imageManager import *

PARA_PATH = os.path.dirname(__file__)

PIC_INDEX = 0


class ImageDevGui(QtWidgets.QWidget):
    update_para_signal = QtCore.pyqtSignal(int, dict)
    img_type = ["bmp", "jpg", "gif", "png", "jpeg"]
    index = 0

    def __init__(self, parent=None):
        super(ImageDevGui, self).__init__(parent)
        self.imgMat = None
        self.filedir = ''
        self.filename = []
        self.img_index = 0
        self.func_name = ""
        parafile = os.path.join(PARA_PATH, "device_para.json")
        with open(parafile, "r", encoding='utf-8') as f:
            self.para_list = json.loads(f.read())

    def setPara(self, index, para):
        self.index = index
        if para is not None:
            self.para_list = para
            self.filedir = self.para_list["filedir"]
            self.savePathLineEdit.setText(self.filedir)
            self.filename = self.para_list["filename"]

    def setFunctionName(self, name):
        self.func_name = name

    def setImg(self, img):
        self.imgMat = copy.deepcopy(img)

    def convertQtImg(self, imgMat):
        if len(imgMat.shape) == 3:
            img = cv2.cvtColor(imgMat, cv2.COLOR_BGR2RGB)
        else:
            img = cv2.cvtColor(imgMat, cv2.COLOR_GRAY2RGB)
        h, w = img.shape[:2]
        h = (h + 3) // 4
        w = (w + 3) // 4
        shrink = cv2.resize(img, (4 * w, 4 * h), interpolation=cv2.INTER_AREA)
        QtImg = QtGui.QImage(shrink.data,
                             shrink.shape[1],
                             shrink.shape[0],
                             QtGui.QImage.Format_RGB888)
        return QtImg

    def initUI(self):
        openLabel = QtWidgets.QLabel(self)
        openLabel.setText("path:")
        self.savePathLineEdit = QtWidgets.QLineEdit(self)
        browebtn = QtWidgets.QPushButton(self)
        browebtn.setText("browse")

        hbox1 = QtWidgets.QHBoxLayout()
        hbox1.addWidget(openLabel)
        hbox1.addWidget(self.savePathLineEdit)
        hbox1.addWidget(browebtn)

        browebtn.clicked.connect(self.browebtn_clicked)

        btn_open = QtWidgets.QPushButton(self)
        btn_open.setText("open")
        btn_open.clicked.connect(self.btn_open_clicked)

        btn_next = QtWidgets.QPushButton(self)
        btn_next.setText("next")
        btn_next.clicked.connect(self.btn_next_clicked)

        hbox2 = QtWidgets.QHBoxLayout()
        hbox2.addWidget(btn_open)
        hbox2.addWidget(btn_next)

        btn_ok = QtWidgets.QPushButton(self)
        btn_ok.setText("ok")
        btn_ok.clicked.connect(self.btn_ok_clicked)

        btn_cancel = QtWidgets.QPushButton(self)
        btn_cancel.setText("cancel")
        btn_cancel.clicked.connect(self.btn_cancel_clicked)

        hbox3 = QtWidgets.QHBoxLayout()
        hbox3.addWidget(btn_ok)
        hbox3.addWidget(btn_cancel)

        vbox = QtWidgets.QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addLayout(hbox2)
        vbox.addStretch(12)
        vbox.addLayout(hbox3)

        self.setLayout(vbox)

    def browebtn_clicked(self):
        # QFileDialog.getExistingDirectory()
        # filename = QFileDialog.getOpenFileName(self, "Open file", "..", "Image files(*.bmp *.jpg *.gif *.png *.jpeg)")
        self.filedir = QFileDialog.getExistingDirectory(self, "Open file", "..")
        self.savePathLineEdit.setText(self.filedir)
        if os.path.isdir(self.filedir):
            for root, dirs, files in os.walk(self.filedir, topdown=False):
                for name in files:
                    print('file:' + os.path.join(root, name))
                    filepath = os.path.join(root, name)
                    kind = filetype.guess(filepath)
                    if kind:
                        if kind.extension in self.img_type:
                            self.filename.append(filepath)
                for name in dirs:
                    print('dir:' + os.path.join(root, name))

    def btn_next_clicked(self):
        fn_len = len(self.filename)
        if fn_len > 0:
            self.img_index = (self.img_index + 1) % fn_len
        filename = self.filename[self.img_index]
        if filename is None:
            return
        img_mng.img = cv2.imread(filename, 1)
        self.imgMat = copy.deepcopy(img_mng.img)
        img_mng.dispImg(self.imgMat)
        img_mng.setOriginMat(self.imgMat)

    def btn_open_clicked(self):
        if self.filedir == "":
            return
        filename = self.filename[0]
        if filename is None:
            return
        self.imgMat = cv2.imread(filename, 1)
        img_mng.dispImg(self.imgMat)
        img_mng.setOriginMat(self.imgMat)
        # img = img_mng.getOriginMat()
        # img_mng.showImg("ss", img)
        # quit()

    def btn_ok_clicked(self):
        self.para_list["filedir"] = self.filedir
        self.para_list["filename"] = self.filename
        self.update_para_signal.emit(self.index, self.para_list)
        parafile = os.path.join(PARA_PATH, "device_para.json")
        with open(parafile, "w", encoding='utf-8') as f:
            f.write(json.dumps(self.para_list, indent=4))

    def btn_cancel_clicked(self):
        self.close()

    def run(self, para):
        global PIC_INDEX
        filedir = para["filedir"]
        filename = para["filename"]
        if filedir == '':
            return
        if filename is None:
            return
        len_list = len(filename)
        fn = filename[PIC_INDEX]
        PIC_INDEX = (PIC_INDEX + 1) % len_list
        if os.path.exists(fn):
            self.imgMat = cv2.imread(fn, 0)
            img_mng.setOriginMat(self.imgMat)
            img_mng.dispImg(self.imgMat)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ui = ImageDevGui()
    ui.show()
    sys.exit(app.exec_())
